﻿// Ftp客户端实现.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<stdio.h>
#include<direct.h> // _getcwd
#include<iostream>
#include<winsock2.h>
#include "Ws2tcpip.h"
#include <fstream>
#include<windows.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

int main()
{
	//tcp连接部分
	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested = MAKEWORD(1,1);
	WSAStartup(wVersionRequested, &wsaData);
	SOCKET sockClient = socket(AF_INET,SOCK_STREAM,0);
	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(8888);
	int nRtn = connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
	if (nRtn == SOCKET_ERROR)
	{
		cout << "连接服务器失败！请重试" << endl;
		return -1;
	}
	
	// 在指定的目录下读取创建文件
	char* buffer;
	char absolutePath[MAX_PATH];
	memset(absolutePath, 0, MAX_PATH);
	GetModuleFileNameA(NULL, absolutePath, MAX_PATH);
	string strPath = (std::string)absolutePath;
	int nPos = strPath.find_last_of('\\', strPath.length());
	string strDirectory = strPath.substr(0, nPos);  // 返回不带有可执行文件名的路径
	char* pFileName = "\\1.txt";
	buffer = const_cast<char*>(strDirectory.c_str());
	strcat(buffer, pFileName);
	std::fstream fs;
	fs.open(buffer, std::ios::in);
	if (!fs)
	{
		ofstream fout(buffer);
		if (fout)
		{
			for (int i = 0; i < 100000; i++)
			{
				fout << "写入内容，也可以不写入" << endl;
			}
			fout.close();
		}
	}
	else
	{
		cout << "该文件已经存在！" << endl;
	}
	//Ftp Client读取文件的长度
	FILE* fp=fopen(buffer,"rt");
	fseek(fp,0,SEEK_END);
	int totalSize = ftell(fp);
	fclose(fp);

	//ftp Client发送文件长度
	char fileSizeChr[20] = {0};
	_itoa(totalSize, fileSizeChr,10);
	send(sockClient, fileSizeChr,strlen(fileSizeChr)+1,0);

	//ftp client发送文件
	fp = fopen(buffer,"rt");
	int readSize = 0;
	int sendTotalSize = 0;
	char sendBuf[1024] = { 0 };
	while ((readSize=fread(sendBuf,1,sizeof(sendBuf),fp))>0)
	{
		send(sockClient, sendBuf, readSize, 0);
		sendTotalSize += readSize;
		printf("Send %d MB\n", sendTotalSize/(1024*1024));
	}
	fclose(fp);
	if (sendTotalSize == totalSize)
	{
		printf("Done!");
	}
	else
	{
		printf("Error!");
	}
	
	closesocket(sockClient);
	WSACleanup();
	getchar();
    return 0;
}

